#include <iostream>
#include <thread>
#include <stop_token>
#include <chrono>

void worker(std::stop_token token) {
    // 注册回调函数进行资源清理
    std::stop_callback callback(token, []() {
        std::cout << "Callback: Releasing resources...\n";
    });

    while (!token.stop_requested()) {
        std::cout << "Worker is executing...\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    std::cout << "Worker is stopping.\n";
}

int main() {
    std::jthread jt(worker);

    std::this_thread::sleep_for(std::chrono::seconds(2));
    // jt析构时自动发出停止请求并执行回调
    return 0;
}
